package com.zp.game

import android.graphics.Bitmap
import game.engine.base.Director
import game.engine.base.Sprite
import game.engine.base.anim.composition.Parallel
import game.engine.base.anim.delay
import game.engine.base.anim.repeat
import game.engine.base.anim.rotateTo
import game.engine.base.anim.scaleTo
import game.engine.base.anim.single.Delay
import game.engine.base.anim.single.RotateTo
import game.engine.base.anim.single.ScaleTo

enum class ZpHbState {
    AlreadyGet, // 已领取
    CanGet, // 可以领取,但是还没有领
    CanNotGet, // 还没到达领取条件
}

// 3个状态
class ZpHb(
        val idx:Int,
        val alreadyGetBitmap: Bitmap,
        val activeBitmap: Bitmap,
        val inActiveBitmap: Bitmap,
        val targetValue: Int,
        private var state: ZpHbState = ZpHbState.CanNotGet,
) : Sprite(inActiveBitmap) {


    // 更新状态
    fun udpateState(awardState:Int,curValue: Int) {

        val tweenManager = Director.instance.curScene!!.tweenManager

        // 先删除动画
        tweenManager.removeTweenByNode(this)

        if (awardState > 0){
            // 已领取
            bitmap = alreadyGetBitmap
            state = ZpHbState.AlreadyGet
        }else{

            if (curValue >= targetValue){

                // 可以领取
                bitmap = activeBitmap
                state = ZpHbState.CanGet

                // 播放动画
                val tween1 = ScaleTo(0.25f, 0.8f, 0.8f)
                        .scaleTo(0.25f, 1f, 1f)
                        .delay(0.5f)

                val tween2 = RotateTo(0.1f, -5f)
                        .rotateTo(0.1f, -5f)
                        .rotateTo(0.1f, 5f)
                        .rotateTo(0.1f, -5f)
                        .rotateTo(0.1f, 5f)
                        .rotateTo(0.1f, -5f)
                        .rotateTo(0.1f, 5f)
                        .rotateTo(0.1f, -5f)
                        .rotateTo(0.1f, 5f)
                        .rotateTo(0.1f, -5f)
                        .rotateTo(0.1f, 5f)
                        .rotateTo(0.1f, 0f)

                Delay(0.2f)
                        .repeat(-1, Parallel(tween1, tween2))
                        .runBy(this)

            }else{
                // 还没够领取的条件
                bitmap = inActiveBitmap
                state = ZpHbState.CanNotGet
            }
        }
    }


    private fun canGet():Boolean{
        return state == ZpHbState.CanGet
    }

    fun isConsumeTouchEvent(touchX:Float,touchY:Float):Boolean{
        if (canGet()){
            val rect = transformLocalRectToWorldRect(parent!!,getBoundingBox())
            if (rect.contains(touchX,touchY)){
                val zpGame = Director.instance.gameApp.activity as ZpGame
                zpGame.handler.post {
                    // 显示一个dialog
                    PacketDialog(zpGame,idx).show()
                }
                return true
            }
        }
        return  false
    }
}